package com.sy.core.web;

import com.alibaba.fastjson.JSONObject;
import com.sy.core.model.SysUser;
import com.sy.core.util.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 登录控制
 *
 * @Author :Chong.CaiXin
 * @Description :
 * @Date : Created in 14:28 2018/8/21
 */
@Controller
@RequestMapping("user")
public class LoginCtl extends BaseCtl {
    /*@Autowired
    private SysRelationService sysRelationService;*/

    @Resource
    protected RedisTemplate<Object, Object> template;

    @PostMapping(value = "/login")
    @ResponseBody
    //@BussinessLog(description = "系统登入")
    public RestResult loginsystem(SysUser sys, String code,String rememberStatus) {
        //用户名密码登录
        String pass = sys.getPassword();
        if (StringUtils.isNotBlank(sys.getPassword())) {
            if (sys != null && StringUtils.isNotBlank(sys.getPhone())) {
                SysUser sysUser = null;
                Boolean is_phone = false;
                if (sys.getPhone().matches(SysConst.PHONE)) {
                    is_phone = true;
                    sysUser = this.authentication(sys.getPhone());
                } else if(sys.getPhone().matches(SysConst.ACCOUNT)){
                   sysUser = sysUserService.selectUserByAccount(sys.getPhone());
                }else{
                    return new RestResult("691","账号格式不正确,请输入正确的手机号|账号");
                }
                if (sysUser != null) {
                    if(sysUser.getStatus()!=null && sysUser.getStatus()==1){//判断用户状态是否为冻结状态
                        return new RestResult("405","账号已冻结,请联系管理员");
                    }
                    if (StringUtils.isNotBlank(sys.getPassword())) {
                        SysUser ss = null;
                        if(is_phone){
                             sys.setPassword(MD5Util.generate(sys.getPassword(), sysUser.getSalt()));
                             ss = this.authentication(sys);
                        }else{
                            ss = sysUserService.authenticationByAccountAndPasss(sys.getPhone(),MD5Util.generate(sys.getPassword(), sysUser.getSalt()));
                        }

                        if (ss != null) {
                            /*if(StringUtils.isNotBlank(ss.getRolePk())) {
                                SysRole role = sysRelationService.findRecordByRoleId(ss.getRolePk());
                                if(role!=null){
                                    ss.setUd5(role.getUd2());//将用户权限放入用户对象中
                                }
                            }*/
                            setUserInfoToRedis(ss);
                            response.addCookie(productCookie("SYSTEMUSERID",ss.getPk()));
                            if("1".equalsIgnoreCase(rememberStatus)){//1表示点了记住密码,吧加密过的密码存入cookie
                                String encryptionUsername=sys.getPhone();
                                encryptionUsername=Aes.aesEncrypt(encryptionUsername).trim();
                                String encryptionPassword=Aes.aesEncrypt(pass).trim();
                                try {
                                    encryptionUsername= URLEncoder.encode(encryptionUsername,"UTF-8");
                                    encryptionPassword= URLEncoder.encode(encryptionPassword,"UTF-8");
                                } catch (UnsupportedEncodingException e) {
                                    e.printStackTrace();
                                    logger.error(e.toString());
                                }

                                response.addCookie(productCookie("REMEMBER_LOGIN_USERNAME",encryptionUsername));
                                response.addCookie(productCookie("REMEMBER_LOGIN_PASSWORD",encryptionPassword));
                            }
                            return new RestResult("200","登录成功",ss.getPk());
                        }
                        return new RestResult("405","用户名或密码错误");
                    } else {
                        return new RestResult("691","密码不允许为空");
                    }
                } else {
                    return new RestResult("405","登录失败,该手机号码尚未注册");
                }
            }
            return new RestResult("691","用户名不予许为空");
        } else {
            //验证码登录
            if (StringUtils.isNotBlank(sys.getPhone()) && sys.getPhone().matches(SysConst.PHONE)) {
                if (StringUtils.isNotBlank(code)) {
                    SysUser sysUser = this.authentication(sys.getPhone());
                    if (sysUser == null) {
                        return new RestResult("405","登录失败,该手机号码尚未注册");
                    }
                    HashMap<Object, Object> hm = RedisUtil.getValidationCodeFormRedis(template, sys.getPhone());
                    String validationCode = null;
                    if (hm != null && hm.size() > 0) {
                        validationCode = (String) hm.get("2");
                    }
                    if (code.equalsIgnoreCase(validationCode)) {
                        /*if(StringUtils.isNotBlank(sysUser.getRolePk())) {
                            SysRole role = sysRelationService.findRecordByRoleId(sysUser.getRolePk());
                            if(role!=null){
                                sysUser.setUd5(role.getUd2());//将用户权限放入用户对象中
                            }
                        }*/
                        setUserInfoToRedis(sysUser);
                        response.addCookie(productCookie("SYSTEMUSERID",sysUser.getPk()));
                        return new RestResult("200","登录成功");
                    }
                }
                return new RestResult("406","登录失败,验证码错误");
            }
            return new RestResult("405",StringUtils.isNotBlank(sys.getPhone()) ? "登录失败,手机号码格式不正确" : "登录失败,手机号码不允许为空");
        }

    }

    /**
     * 添加用户信息到redis中
     *
     * @param ss
     * @return
     */
    public void setUserInfoToRedis(SysUser ss) {
        //ss.setPassword("");
        RedisUtil.setToRedis(template,ss);
    }



    public Cookie productCookie(String key,String userId) {
        Cookie coo = new Cookie(key, userId);
        coo.setPath("/");
        coo.setMaxAge(1 * 24 * 60 * 60);
        return coo;
    }


    public SysUser authentication(String phone) {
        HashMap<String, Object> map = new HashMap<>();
        if(StringUtils.isNotBlank(phone) && phone.matches(SysConst.PHONE)){
            map.put("phone",phone);
        }
        if(StringUtils.isNotBlank(phone) && phone.matches(SysConst.ACCOUNT)){
            map.put("account",phone);
        }
        if(map!=null && map.size()>0){
            SysUser sys = sysUserService.queryUserByPhone(map);
            return sys;
        }
        return null;
    }

    public SysUser authentication(SysUser sysUser) {

        return sysUserService.authentication(sysUser);
    }

    @RequestMapping("checkUserPassword")
    @ResponseBody
    public RestResult checkUserPassword(SysUser sys){
        SysUser  sysUser = sysUserService.findUserByPk(sys.getPk());
        if(sysUser!=null){
            sys.setPassword(MD5Util.generate(sys.getPassword(), sysUser.getSalt()));
            sys.setPhone(sysUser.getPhone());
            SysUser ss = this.authentication(sys);
            return ss!=null?new RestResult(true,"密码校验成功"):new RestResult(false,"旧密码错误");
        }
        return new RestResult(false,"当前手机号尚未注册");
    }

    /**
     * 修改登录密码
     *
     * @param sysUser
     * @return
     */
    @RequestMapping(value = "reset", method = RequestMethod.POST)
    @ResponseBody
    //@BussinessLog(description = "重设密码")
    public RestResult forgetPasword(SysUser sysUser) {
        if (StringUtils.isNotBlank(sysUser.getPhone()) && sysUser.getPhone().matches(SysConst.PHONE)) {
            if (StringUtils.isNotBlank(sysUser.getPassword()) && sysUser.getPassword().matches(SysConst.PASSWORD)) {
                SysUser sys = this.authentication(sysUser.getPhone());
                if (sys != null) {
                    //重置密码
                    if (sys.getPassword().equalsIgnoreCase(MD5Util.generate(sysUser.getPassword(), sys.getSalt()))) {
                        return new RestResult(false, "新密码不能和原密码一样,请重新输入");
                    } else {
                        sys.setPassword(MD5Util.generate(sysUser.getPassword(), sys.getSalt()));
                        sysUserService.update(sys);
                        RedisUtil.clenUserInfo(template,sys);//清空用户登录信息
                        return new RestResult(true, "密码重置成功");
                    }
                }
                return new RestResult(false, "手机号码未注册,无权执行此操作");
            }else{
                return new RestResult(false, "密码格式有误,请输入6位以上字母加数字组合密码");
            }
        }
        return new RestResult(false, "手机号码格式有误");
    }

    /**
     * 系统登出
     *
     * @return
     */
    @RequestMapping("loginout")
    @ResponseBody
    //@BussinessLog(description = "系统登出")
    public RestResult loginoutSystem() {
        String userId = new CookUtils().getLoginUserId(request);
        Cookie cookie = new Cookie("SYSTEMUSERID", null);
        cookie.setPath("/");
        cookie.setMaxAge(0);
        response.addCookie(cookie);
        if (StringUtils.isNotBlank(userId)) {
            SysUser user = RedisUtil.getFormRedis(template, userId);
            if (user != null) {
                template.delete(SysConst.REDIS_USER_SESSION_KEY + user.getPk());
               // return RestResultGenerator.jsonResult(true, );
                return new RestResult("200","系统登出成功");
            }
           // return RestResultGenerator.jsonResult(false, "非法请求,参数异常");
            return new RestResult("691","非法请求,参数异常");
        }
       // return RestResultGenerator.jsonResult(false, "参数异常");
        return new RestResult("202","参数异常");
    }



    /**
     * 获取登录用户信息
     *
     * @param request
     * @return
     */
    public SysUser getLoginUser(HttpServletRequest request) {
        HttpSession session = request.getSession();
        String uid = (String) session.getAttribute("loginUser");
        if (uid != null) {
            SysUser sys = RedisUtil.getFormRedis(template, uid);
            if (sys != null) {
                return sys;
            }
        }
        return null;
    }

    public Boolean loginCheck(HttpServletRequest request) {
        String userId = new CookUtils().getLoginUserId
                (request);
        return StringUtils.isNotBlank(userId) ? false : true;
    }
}
